const app = getApp();

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const requests = data => {
  let token = wx.getStorageSync('token');
  if ( ! token ) {
      getApp().tokenCallback = token => {
        networks(data, token);  
      }
  } else {
    networks(data, token);
  }
  
}

function networks(data,token){
  let examination_type = wx.getStorageSync('examination_type_active');
  if ( ! examination_type ) {
    examination_type = 1
  }
  if ( ! data.data ) {
    data.data = {};
  }
  data.data.examination_type = examination_type || 1;
  wx.request({
    url: app.globalData.serverUrl+'v1/api/'+data.url,
    method: data.method || 'GET',
    dataType: data.dataType || 'json',
    data: data.data || {},
    header: {
      'token': token
    },
    success: data.success,
    fail: function (data) {
      wx.showToast({
        title: '服务器错误',
        icon: 'none',
        duration: 1500
      })
    },
    complete: data.complete || function(data){
      if ( data.data.code != 200 ) {
        wx.showToast({
          title: data.data.message,
          icon: 'none',
          duration: 1500
        })
      }
    }
  })
}

module.exports = {
  formatTime: formatTime,
  requests: requests
}
